﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Zhaoxi.MongoDBSample.Dtos;
using Zhaoxi.MongoDBSample.Models;
using Zhaoxi.MongoDBSample.Respositories;

namespace Zhaoxi.MongoDBSample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SchoolController : ControllerBase
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IMapper _mapper;

        public SchoolController(IStudentRepository studentRepository, IMapper mapper)
        {
            _studentRepository = studentRepository;
            _mapper = mapper;
        }

        [HttpPost]
        public async Task<IActionResult> Post(StudentForCreateOrUpdateDto student)
        {
            var studentEntity = _mapper.Map<Student>(student);
            var result = await _studentRepository.CreateAsync(studentEntity);
            return Ok(result);
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(string id, [FromServices] ICourseRepository courseRepository)
        {
            var student = await _studentRepository.GetByIdAsync(id);
            if (student == null)
            {
                return NotFound();
            }

            if (student.Courses is not { Count: > 0 }) return Ok(student);

            student.CourseList = new List<Course>();
            foreach (var courseId in student.Courses)
            {
                var course = await courseRepository.GetByIdAsync(courseId);
                if (course != null)
                    student.CourseList.Add(course);
            }

            return Ok(student);
        }

        [HttpGet]
        public async Task<IActionResult> GetStudents()
        {
            var result = await _studentRepository.GetAllAsync();
            return Ok(result);
        }

        [HttpPut]
        public async Task<IActionResult> Put(string id, StudentForCreateOrUpdateDto student)
        {
            var studentEntity = await _studentRepository.GetByIdAsync(id);

            if (studentEntity == null)
            {
                return NotFound();
            }

            _mapper.Map(student, studentEntity);
            await _studentRepository.UpdateAsync(studentEntity);
            return Ok();
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(string id)
        {
            var studentEntity = await _studentRepository.GetByIdAsync(id);

            if (studentEntity == null)
            {
                return NotFound();
            }

            await _studentRepository.DeleteAsync(studentEntity);
            return Ok();
        }
    }
}
